from flask import Flask,jsonify,request
import json
from flask_cors import CORS

app = Flask(__name__)
CORS(app)
#实现orm，对象关系映射
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy(app)

from config import Config
app.config.from_object(Config)

#创建表
class Cate(db.Model):
    id = db.Column(db.Integer,primary_key=True,autoincrement=True)
    name = db.Column(db.String(50),unique=True)
    level = db.Column(db.Integer,default=1)
    pid = db.Column(db.Integer,default=0)#顶级父id 等于0



@app.route('/add',methods=['POST','GET','PUT','DELETE'])
def cateM():
    if request.method == 'POST':
        data = json.loads(request.data)
        cate = Cate(name=data['name'])
        db.session.add(cate)
        db.session.commit()
        return jsonify({"code":200})

    elif request.method == 'GET':
        c = Cate.query.all()
        list = []
        for i in c:
            dict = {}
            dict['id'] = i.id
            dict['name'] = i.name
            list.append(dict)
        return jsonify({"code":200,"list":list})
    elif request.method == 'PUT':
        id = request.args['id']
        name = request.args['name']
        Cate.query.filter_by(id = id).update({'name':name})
        db.session.commit()
        return jsonify({"code":200})

    elif request.method == 'DELETE':
        id = request.args['id']
        Cate.query.filter_by(id=id).delete()
        db.session.commit()
        return jsonify({"code": 200})






if __name__ == '__main__':
    app.run(debug=True)
